<template>
  <div class="group-store">
    <div class="table-title">
      <el-input v-model="searchData.searchValue" style="width:220px;" placeholder="姓名、部门"></el-input>
      <el-button type="primary" @click="initList" data-auth="bloc_user_query">查询</el-button>
			<el-button type="primary" @click="handleAdd" data-auth="bloc_user_add">添加员工</el-button>
    </div>
    <div class="table-content">
      <el-table
        border
        :data="tableData"
        style="width: 100%">
        <el-table-column
          label="姓名"
          prop="Name">
        </el-table-column>
        <el-table-column
          label="手机号"
          prop="Mobile">
        </el-table-column>
        <el-table-column
          label="部门">
          <template slot-scope="scope">
            {{scope.row.OrganizationName}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250px">
          <template slot-scope="scope">
						<el-button
              size="mini"
							type="primary"
              @click="handleEdit(scope.row)" data-auth="bloc_user_modify">编辑</el-button>
						<el-button
              size="mini"
							type="primary"
              @click="handleRole(scope.row)" data-auth="bloc_user_addrole">添加角色</el-button>
						<el-button
              size="mini"
              @click="handleDelete(scope.row)" data-auth="bloc_user_delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="table-page">
			<el-pagination
			  background
				@size-change="changePage"
      	@current-change="getList"
      	:current-page.sync="searchData.index"
      	:page-sizes="[100, 200, 300, 400]"
			  layout="total,prev, pager, next"
			  :total="pageTotal">
			</el-pagination>
    </div>

		<el-dialog
			:title="dialogTitle"
			:visible.sync="roomShow"
			width="560px"
			center>
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
				<el-form-item label="姓名：" prop="Name">
					<el-input v-model="ruleForm.Name"></el-input>
				</el-form-item>
        <el-form-item label="手机号：" prop="Mobile">
					<el-input v-model="ruleForm.Mobile" maxlength="11"></el-input>
				</el-form-item>
        <el-form-item label="部门：" prop="OrganizationName">
					<div class="show-tree">
            <el-input v-model="ruleForm.OrganizationName" @focus="showtree=true" readonly></el-input>
  					<div class="select-tree">
              <el-tree :data="OrganiLists" @node-click="handleNodeClick"></el-tree>
            </div>
          </div>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="btnSave('ruleForm')">保存</el-button>
				<el-button @click="roomShow = false">取 消</el-button>
			</span>
		</el-dialog>

    <el-dialog
			:title="dialogTitle"
			:visible.sync="roleShow"
			width="700px"
			center>
      <div class="setroom-div">
        <el-checkbox-group v-model="RoleIdList">
          <div v-for="item in roleData" style="margin-bottom:15px;">
            <span style="font-size:14px;min-width:150px;display:inline-block;">{{item.StoreName}}：</span>
            <el-checkbox :label="item.StoreId+' '+n.Id" v-for="n in item.RoleList" :key="n.Id">{{n.Name}}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="saveRole('ruleForm')">保存</el-button>
				<el-button @click="roleShow = false">取 消</el-button>
			</span>
		</el-dialog>

  </div>
</template>
<script>
  export default {
    data () {
      return {
        showtree:false,
        roleShow:false,
        roleData:[],
        RoleIdList:[],
        OrganiLists:[],
        pageTotal:0,
        searchData:{
          returnStoreRoles:true,
					searchValue:'',
          index:1,
          size:10
        },
				dateTime:[],
        tableData:[],
				infoShow:false,
				userInfoData:{},
				dialogTitle:'',
				roomShow:false,
				ruleForm: {
          Name: "",
          OrganizationName:"",
          OrganizationId:"",
          Mobile:""
        },
        rules: {
          Name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ],
          Mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
          ],
          OrganizationName: [
            { required: true,message: '请选择所属部门', trigger: 'change' }
          ],
        }
      }
    },
    created(){
      this.initList();
      this.$ajax.GetAllDepartment().then(res=>{
        if(res.Success){
          this.OrganiLists=res.Data;
        }
      })
      this.$ajax.GetCurrentUserRoles().then(res=>{
        if(res.Success){
          this.roleData=res.Data.StoreList;
        }
      })
    },
    methods:{
      handleNodeClick(row){
        this.ruleForm.OrganizationName=row.label;
        this.ruleForm.OrganizationId=row.id;
      },
      initList(){
        this.roomShow=false;
				this.infoShow=false;
				this.roleShow=false;
        this.getList();
      },
      changePage(size){
        this.searchData.index=1;
        this.searchData.size=size;
        this.getList();
      },
      getList(){
        this.$ajax.GetUsersListByPage(this.searchData).then(res=>{
          if(res.Success){
            this.tableData=res.Data.PagedData;
            this.pageTotal=res.Data.TotalCount;
          }
        })
      },
      resetForm(formName) {
        if(!this.$refs[formName]){return};
        this.$refs[formName].resetFields();
      },
			handleExcel(){
				let data=_.cloneDeep(this.searchData);
				data=this.$urlEncode(data);
				window.open(this.$api.GetMemberListToExcel+'?'+data);
			},
			handleAdd() {
        this.dialogTitle='添加账号';
        this.resetForm('ruleForm');
        this.ruleForm={
          Name: "",
          OrganizationName:"",
          OrganizationId:"",
          Mobile:""
        };
        this.roomShow=true;
      },
      handleEdit(row) {
        this.dialogTitle='编辑账号';
        this.resetForm('ruleForm');
				this.ruleForm=_.cloneDeep(row);
				this.roomShow=true;
      },
      handleDelete(row) {
        this.deleteShow('确认删除此员工?',row.Id,'deleteuser')
      },
      deleteShow(title,id,api){
        this.$confirm(title, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          let data={
            id:id
          };
          this.$ajax[api](data).then(res=>{
            if(res.Success){
              this.$message({
                type: 'success',
                message: '已删除!'
              });
              this.initList();
            }
          })
        }).catch(() => {
        });
      },
			btnSave(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$ajax.saveuser(this.ruleForm).then(res=>{
              if(res.Success){
                this.$message.success(this.dialogTitle+'成功!');
                this.$refs[formName].resetFields();
                this.initList();
              }
            })
          } else {
            return false;
          }
        });
      },
			handleRole(row){
        this.$ajax.getuser({id:row.Id,returnStoreRoles:true}).then(res=>{
          if(res.Success){
            this.RoleIdList=[];
            if(!!res.Data.Roles){
              res.Data.Roles.StoreList.forEach(item=>{
                item.RoleList.forEach(val=>{
                  this.RoleIdList.push(item.StoreId+' '+val.Id)
                })
              });
            }
            this.dialogTitle='设置角色';
            this.UserId=row.Id;
    				this.roleShow=true;
          }
        })
			},
      saveRole(){
        let data={
          UserId:this.UserId,
          StoreRoleList:[]
        }
        let Ids={}
        this.RoleIdList.forEach(val=>{
          if(Ids[val.split(' ')[0]]){
            Ids[val.split(' ')[0]].RoleIdList.push(
              parseInt([val.split(' ')[1]])
            )
          }else{
            Ids[val.split(' ')[0]]={
              Id:parseInt(val.split(' ')[0]),
              RoleIdList:[parseInt(val.split(' ')[1])]
            }
          }
        })
        data.StoreRoleList=Object.keys(Ids).map(k=>{
          return Ids[k]
        })
        this.$ajax.AttributeUserRoles(data).then(res=>{
          if(res.Success){
            this.$message.success(this.dialogTitle+'成功!');
            this.initList();
          }
        })
      }
    }
  }
</script>
